from django.contrib.auth.backends import ModelBackend

import re

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from meiduo_mall.apps.users.models import User
from django.conf import settings


# class UserModelBackend(ModelBackend):
#     """自定义用户认证后端"""
#     # 重写用户认证的方法
#     def authenticate(self, request, username=None, password=None, **kwargs):
#         """
#         :param request:
#         :param username:   手机号或者验证码
#         :param password:   密码明文
#         :param kwargs:   额外参数
#         :return:  user
#         """
#         # 使用账号查询用户(判断是用户名或者手机号)
#         try:
#             if re.match(r'^1[3-9]\d{9}}$', username):
#                 user = User.objects.get(mobile=username)
#             else:
#                 user = User.objects.get(username=username)
#         except User.DoesNotExist:
#             return None
#         # 如果可以查询到，需要校验密码
#         else:
#             if user and user.check_password(password):
#                 return user
#             else:
#                 return None


def get_user_by_account(account):
    """
    根据account查询用户
    :param account: 用户名或者手机号
    :return: user
    """
    try:
        if re.match('^1[3-9]\d{9}$', account):
            # 手机号登录
            user = User.objects.get(mobile=account)
        else:
            # 用户名登录
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UserModelBackend(ModelBackend):
    """自定义用户认证后端"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写认证方法，实现多账号登录
        :param request: 请求对象
        :param username: 用户名
        :param password: 密码
        :param kwargs: 其他参数
        :return: user
        """
        # 根据传入的username获取user对象。username可以是手机号也可以是账号
        user = get_user_by_account(username)
        # 校验user是否存在并校验密码是否正确
        if user and user.check_password(password):
            return user


def generate_verify_email_url(user):
    """
    生成邮箱验证链接
    :param user: 当前登录用户
    :return: verify_url
    """
    # print(settings.EMAIL_HOST_PASSWORD)
    serializer = Serializer(settings.EMAIL_HOST_PASSWORD, expires_in=60 * 60 * 24)
    data = {'user_id': user.id, 'email': user.email}
    token = serializer.dumps(data).decode()

    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url
